<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名：">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="密码：" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-row>
      <el-col :span="10" style="display: flex; align-content: center; height: 38px">
        <div
            class="kaptcha_wrapper"
            :style="`background-size: cover; background-position: center; background-repeat: no-repeat; background-image: url('${kapatchImage}'); `"
            @click="getKaptcha"
        />
      </el-col>
      <el-col :span="2" />
      <el-col :span="12">
        <el-form-item prop="verify_code">
          <el-input v-model="loginForm.verify_code" placeholder="验证码：">
            <template #prefix>
              <el-icon class="el-input__icon">
                <lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import {getKeepAliveRouterNames, getTimeState} from "@/helper";
import { ElNotification } from "element-plus";
import { kaptchaApi } from "@/api/modules/common";
import { loginApi } from "@/api/modules/login";
import { operationsApi, menuListApi } from "@/api/modules/sys_user.ts";
import { authStore } from "@/stores/modules/auth";
import { useTabsStore } from "@/stores/modules/tabs";
import { routerStore } from "@/stores/modules/router";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import {LoginForm} from "@/interface/api";

const router = useRouter();
const authState = authStore();
const tabsStore = useTabsStore();
const routerState = routerStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  verify_code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<LoginForm>({
  username: "",
  password: "",
  uid: "",
  verify_code: ""
});

const verifyCodeData = reactive({
  uid: "",
  image: ""
});
const kapatchImage = ref("");

onMounted(() => {
  getKaptcha();
});

const getKaptcha = () => {
  kaptchaApi({ width: 175, height: 38 }).then((res: any) => {
    const { data } = res;
    verifyCodeData.uid = data.uid;
    verifyCodeData.image = data.image;
    kapatchImage.value = `data:image/png;base64,${data.image}`;
  });
};

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const res = await loginApi({ ...loginForm, uid: verifyCodeData.uid });
      authState.setToken(res.data.token);
      authState.setUser(res.data.user);

      // 2.初始化用户菜单
      const { data } = await menuListApi();
      authState.setMenuList(data);
      routerState.setKeepAliveNames(getKeepAliveRouterNames(authState.flatMenuList));

      // 3.初始化用户操作权限
      const resultData = await operationsApi();
      authState.setOperations(resultData.data);

      // 4.清空 tabs 数据
      await tabsStore.closeMultipleTab();

      // 5.跳转到首页
      await router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录 Blog-Admin",
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
.kaptcha_wrapper {
  width: 100%;
  height: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}
</style>
